import Vue from 'vue';
import Vuex from 'vuex';
import global from './global';

Vue.use(Vuex);

const getFileModule = (files) => {
  const module = files.keys().reduce((modules, path) => {
    // 'modules/index.js' => 'index'
    // 'modules/xxx/index.js' => 'xxx'
    // 'modules/xxx/app.js' => 'xxx/app'
    const name = path.replace(/^\.\/(.*)\.\w+$/, '$1').replace(/(.*)\/index$/, '$1');
    const value = files(path);
    modules[name] = value.default;

    return modules;
  }, {});

  return module;
};

// https://webpack.js.org/guides/dependency-management/#requirecontext
const moduleFiles = require.context('./modules', true, /\.js$/);
const globalModuleFiles = require.context('./global/modules', true, /\.js$/);
// console.log('moduleFiles', moduleFiles, 'globalModuleFiles', globalModuleFiles);
export default new Vuex.Store({
  ...global,
  modules: { ...getFileModule(moduleFiles), ...getFileModule(globalModuleFiles) }
});
